package com.diyunapp.xilinapp.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.UserBean;
import com.diyunapp.xilinapp.details.GetAllTypeListService;
import com.diyunapp.xilinapp.fragments.BuyCarFragment;
import com.diyunapp.xilinapp.fragments.IndexFragment;
import com.diyunapp.xilinapp.fragments.MineFragment;
import com.diyunapp.xilinapp.fragments.SortFragment;
import com.diyunapp.xilinapp.selfdefine.SearchDBHelper;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends StatusBarFragmentActivity implements View.OnClickListener {

    @Bind(R.id.bottom_home_img)
    ImageView bottomHomeImg;
    @Bind(R.id.bottom_home_txt)
    TextView bottomHomeTxt;
    @Bind(R.id.bottom_home_ll)
    LinearLayout bottomHomeLl;
    @Bind(R.id.bottom_type_img)
    ImageView bottomTypeImg;
    @Bind(R.id.bottom_type_txt)
    TextView bottomTypeTxt;
    @Bind(R.id.bottom_type_ll)
    LinearLayout bottomTypeLl;
    @Bind(R.id.bottom_shoppingcart_img)
    ImageView bottomShoppingcartImg;
    @Bind(R.id.bottom_shoppingcart_txt)
    TextView bottomShoppingcartTxt;
    @Bind(R.id.bottom_shoppingcart_ll)
    LinearLayout bottomShoppingcartLl;
    @Bind(R.id.bottom_mine_img)
    ImageView bottomMineImg;
    @Bind(R.id.bottom_mine_txt)
    TextView bottomMineTxt;
    @Bind(R.id.bottom_mine_ll)
    LinearLayout bottomMineLl;

    private Fragment mTabHome;
    private Fragment mTabType;
    private Fragment mTabBuyCar;
    private Fragment mTabMine;

    private View head_status_view;

    //APP退出操作按钮
    private long mWaitTime = 2000;
    private long mTochTime = 0;

    private SharedPreferences sp;
    public static UserBean myLogin = new UserBean(false);
    public static String url="http://www.xilingou.com/mobile/index.php?";
    private String loginKey;
    private String member_id;
    private String user_name;

    //本地数据库相关变量
    public static SearchDBHelper myDBHelper;
    public static boolean isFreshed = false;
    public static boolean isinFreshing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        sp = getSharedPreferences("xilinshangchengSP", MODE_PRIVATE);
        boolean haveLogin = sp.getBoolean("haveLogin",false);
        loginKey = sp.getString("key","");
        member_id = sp.getString("member_id","");
        user_name = sp.getString("username","");
        if(haveLogin && (!loginKey.isEmpty()) && (!member_id.isEmpty()))
        {
            myLogin.setLoginState(true);
            myLogin.setMemberid(member_id);
            myLogin.setLoginkey(loginKey);
            myLogin.setUsername(user_name);
        }
        else
        {
            myLogin.setLoginState(false);
            sp.edit().putBoolean("haveLogin",false).commit();
        }

        /*
           沉浸式状态栏功能实现说明：
           //设置状态栏透明，即隐藏掉系统自带的状态栏
           1. window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
							WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//激活对状态栏的自定义设置
		   2. tintManager.setStatusBarTintEnabled(true);
		   //给状态栏设置指定的颜色
		   3. tintManager.setTintColor(getResources().getColor(R.color.domain_orange));

		   如果执行了上述功能，需要通过以下两种方式实现状态栏的处理才能正常使用，两者只可选其一
		   方法一.在页面布局中增加属性设置android:fitsSystemWindows="true"
		   方法二.如下解决状态栏占空的问题
                if (android.os.Build.VERSION.SDK_INT > 18)
                {
                    statusbar_view = myView.findViewById(R.id.actionbar_status_bar);
                    statusbar_view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,sbar));
                    statusbar_view.setVisibility(View.VISIBLE);
                }
         */
        head_status_view = findViewById(R.id.mainactivity_menubar_inc);
        super.MenuWidget(head_status_view);

        bottomHomeLl.setOnClickListener(this);
        bottomTypeLl.setOnClickListener(this);
        bottomShoppingcartLl.setOnClickListener(this);
        bottomMineLl.setOnClickListener(this);

        clickFragment(1);

        //创建数据库
        myDBHelper = new SearchDBHelper(this,"xilinmarket.db",null,2);

        if(!isFreshed)
        {
            Intent alltype = new Intent(this,GetAllTypeListService.class);
            startService(alltype);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.bottom_home_ll:
                clickFragment(1);
                break;
            case R.id.bottom_type_ll:
                clickFragment(2);
                break;
            case R.id.bottom_shoppingcart_ll:
                clickFragment(3);
                break;
            case R.id.bottom_mine_ll:
                clickFragment(4);
                break;
            default:
                break;

        }
    }

    void clickFragment(int fragmentFlag)
    {
        clearBottom();
        switch (fragmentFlag) {
            case 1:
                bottomHomeLl.setBackgroundColor(getResources().getColor(R.color.light_orange));
                bottomHomeImg.setImageResource(R.drawable.bottom_home_selected);
                bottomHomeTxt.setTextColor(getResources().getColor(R.color.domain_orange));
                selectFragment(1);
                break;
            case 2:
                bottomTypeLl.setBackgroundColor(getResources().getColor(R.color.light_orange));
                bottomTypeImg.setImageResource(R.drawable.bottom_type_selected);
                bottomTypeTxt.setTextColor(getResources().getColor(R.color.domain_orange));
                selectFragment(2);
                break;
            case 3:
                bottomShoppingcartLl.setBackgroundColor(getResources().getColor(R.color.light_orange));
                bottomShoppingcartImg.setImageResource(R.drawable.bottom_buycar_selected);
                bottomShoppingcartTxt.setTextColor(getResources().getColor(R.color.domain_orange));
                selectFragment(3);
                break;
            case 4:
                bottomMineLl.setBackgroundColor(getResources().getColor(R.color.light_orange));
                bottomMineImg.setImageResource(R.drawable.bottom_user_selected);
                bottomMineTxt.setTextColor(getResources().getColor(R.color.domain_orange));
                selectFragment(4);
                break;
            default:
                break;
        }
    }

    private void selectFragment(int flagInt)
    {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (flagInt)
        {
            case 1:
                if (mTabHome == null) {
                    mTabHome = new IndexFragment();
                    transaction.add(R.id.main_framlayout, mTabHome);
                } else {
                    transaction.show(mTabHome);
                }
                break;
            case 2:
                mTabType = new SortFragment();
                transaction.add(R.id.main_framlayout, mTabType);
                break;
            case 3:
                if (mTabBuyCar == null) {
                    mTabBuyCar = new BuyCarFragment();
                    transaction.add(R.id.main_framlayout, mTabBuyCar);
                } else {
                    transaction.show(mTabBuyCar);
                }
                break;
            case 4:
                if (mTabMine == null) {
                    mTabMine = new MineFragment();
                    transaction.add(R.id.main_framlayout, mTabMine);
                } else {
                    transaction.show(mTabMine);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mTabHome != null) {
            transaction.hide(mTabHome);
        }
        if (mTabType != null) {
            transaction.remove(mTabType);
            mTabType = null;
        }
        if (mTabBuyCar != null) {
            transaction.hide(mTabBuyCar);
        }
        if (mTabMine != null) {
            transaction.hide(mTabMine);
        }
    }

    //清除底部图标的选中状态
    private void clearBottom() {
        bottomHomeLl.setBackgroundColor(getResources().getColor(R.color.domain_orange));
        bottomTypeLl.setBackgroundColor(getResources().getColor(R.color.domain_orange));
        bottomShoppingcartLl.setBackgroundColor(getResources().getColor(R.color.domain_orange));
        bottomMineLl.setBackgroundColor(getResources().getColor(R.color.domain_orange));
        bottomHomeImg.setImageResource(R.drawable.bottom_home);
        bottomTypeImg.setImageResource(R.drawable.bottom_type);
        bottomShoppingcartImg.setImageResource(R.drawable.bottom_buycar);
        bottomMineImg.setImageResource(R.drawable.bottom_user);
        bottomHomeTxt.setTextColor(getResources().getColor(R.color.white));
        bottomTypeTxt.setTextColor(getResources().getColor(R.color.white));
        bottomShoppingcartTxt.setTextColor(getResources().getColor(R.color.white));
        bottomMineTxt.setTextColor(getResources().getColor(R.color.white));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - mTochTime) >= mWaitTime) {
                Toast.makeText(MainActivity.this, "再按返回键退出应用！",
                        Toast.LENGTH_SHORT).show();
                mTochTime = currentTime;
            } else {
                myDBHelper.getReadableDatabase().close();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
